// pages/center/entrust/entrust.js
const wxapi = require("../../../utils/wxapi");
import { Util } from "../../../utils/util";
const { API_SNZO_URL, API_SNZO_FILE_URL } = require("../../../utils/wxapi");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    listOfData: [],
    purposeOfData: [],
    snzoImgUrl: API_SNZO_FILE_URL,
    pageParams: { pageNum: 1, pageSize: 15 },
    purposePageParams: { pageNum: 1, pageSize: 15 },
    total: 0,
    showLogistics: false,
    logisticsInfo: {},
    userType: 'sellUser',
    okText: null,
    showOrder: false,
    orderInfo: null,
    item: null,
    entrustStatus: null,
    showEntrust: false,
    entrustInfo: null,
    yesOrNo: null,
    showPhonecode: false,
    isTriggered: false,
    isHandle: false,
    tabType: 'entrust'
  },

  /**
   * 菜单切换
   * @param {*} e 
   */
  tabChange(e) {
    const tabType = e.currentTarget.dataset.tabType;
    this.setData({
      tabType
    })
    if (tabType === 'entrust') {
      this.getEntrustData();
    } else if (tabType === 'purpose') {
      this.getPurposeData();
    }
  },

  /**
   * 获取数据
   */
  getEntrustData() {
    const bodyParams = Util.trimNulls({
      stk: app.globalData.userInfo.cardNo,
      isLive: 1,
      item: this.data.item,
      standby4: this.data.entrustStatus,
    });
    wxapi.selectEntrustMsg(bodyParams, this.data.pageParams).then(res => {
      wx.hideLoading();
      this.setData({
        isTriggered: false
      })
      if (res.status === 200) {
        if (this.data.pageParams.pageNum === 1) {
          this.data.listOfData = [];
          this.setData({
            scrollTop: 0
          })
        }
        const listOfData = res.data.seachList;
        const newData = this.data.listOfData.concat(listOfData);
        this.setData({
          listOfData: newData,
          total: res.data.seachTotal,
          canScroll: true
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.msg,
          showCancel: false
        })
      }
    })
  },

  /**
   * 获取意向购买数据
   */
  getPurposeData() {
    const bodyParams = Util.trimNulls({
      stk: app.globalData.userInfo.cardNo
    });
    wxapi.selectPurposeFront(bodyParams, this.data.purposePageParams).then(res => {
      wx.hideLoading();
      this.setData({
        isTriggered: false
      })
      if (res.status === 200) {
        if (this.data.purposePageParams.pageNum === 1) {
          this.data.purposeOfData = [];
          this.setData({
            scrollTop: 0
          })
        }
        const purposeOfData = res.data.seachList;
        const newData = this.data.purposeOfData.concat(purposeOfData);
        this.setData({
          purposeOfData: newData,
          total: res.data.seachTotal,
          canScroll: true
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.msg,
          showCancel: false
        })
      }
    })
  },

  /**
   * 滑到最底部加载 获取分页数据
   */
  scrollToLower() {
    if (this.data.listOfData.length === this.data.total) {
      return;
    }
    this.setData({
      canScroll: false
    })
    wx.showLoading({
      title: '加载更多..',
    })
    setTimeout(() => {
      if (this.data.tabType === 'entrust') {
        this.data.pageParams.pageNum++
        this.getEntrustData()
      } else if (this.data.tabType === 'purpose') {
        this.data.purposePageParams.pageNum++
        this.getPurposeData()
      }
    }, 1000);
  },

  /**
   * 下拉刷新
   */
  refresherToLoad() {
    wx.showToast({
      title: '加载中...',
    })
    setTimeout(() => {
      if (this.data.tabType === 'entrust') {
        this.data.pageParams.pageNum = 1;
        this.getEntrustData()
      } else if (this.data.tabType === 'purpose') {
        this.data.purposePageParams.pageNum = 1;
        this.getPurposeData()
      }
    }, 1000);
  },

  /**
   * 预览艺术品
   * @param {*} e 
   */
  previewImage(e) {
    const worksItem = e.currentTarget.dataset.worksItem;
    wx.previewMedia({
      sources: [
        {
          url: this.data.snzoImgUrl + worksItem.worksPhotoUrl
        }
      ],
    })
  },

  /**
   * 查看委托书
   * @param {*} e 
   */
  previewEntrust(e) {
    const item = e.currentTarget.dataset.entrustInfo;
    wx.downloadFile({
      url: API_SNZO_FILE_URL + item.entrustBookUrl,
      success: function (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) { }
        })
      },
      fail: function (res) {
        wx.showModal({
          title: null,
          content: '获取委托书失败',
          cancelText: null
        })
      }
    })
  },

  /**
   * 修改价格
   * @param e 
   */
  resetEntrustPrice(e) {
    const entrustInfo = e.currentTarget.dataset.entrustInfo;
    this.setData({
      showEntrust: true,
      entrustInfo
    })
  },

  /**
   * 确定委托
   * @param {*} e 
   */
  confirmEntrust(e) {
    if (this.data.isHandle) {
      return;
    }
    const entrustValue = e.detail.entrustInfo;
    if (!entrustValue.expectPrice) {
      wx.showModal({
        title: '提示信息',
        content: '请填写意向价格',
        showCancel: false
      })
    }
    wx.showModal({
      title: '提示信息',
      content: '如果您确认修改委托价格，原委托订单会被撤销。',
      complete: (res) => {
        if (res.confirm) {
          const bodyParams = {
            entrustId: this.data.entrustInfo.id,
            updatePrice: entrustValue.expectPrice
          }
          wxapi.updateEntrustPriceBeforePush(bodyParams).then(res => {
            if (res.status === 200) {
              if (res.data) {
                this.sendNotifySms(this.data.entrustInfo, res.data[0]);
              }
              if (this.data.entrustInfo.item === 1) {
                wx.showLoading({
                  title: '支付中',
                })
                const body = Object.assign(this.data.entrustInfo, { expectPrice: entrustValue.expectPrice });
                // 支付
                const openId = wx.getStorageSync('openId');
                if (openId) {
                  // 委托购买
                  this.payEntrust({ openId }, body);
                } else {
                  wx.login({
                    success: (res) => {
                      if (res.code) {
                        const jsCode = res.code;
                        const headers = {
                          'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
                        }
                        wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
                          if (res.code === 20000) {
                            if (res.data) {
                              wx.setStorageSync('openId', res.data);
                              // 委托购买
                              this.payEntrust({ openId: res.data }, body);
                            } else {
                              wx.hideLoading()
                              this.setData({
                                isPaySubmit: false
                              })
                              wx.showToast({
                                title: '获取openId失败',
                                icon: 'error'
                              })
                            }
                          } else {
                            wx.hideLoading();
                            wx.showModal({
                              title: '提示信息',
                              content: res.message,
                              showCancel: false
                            })
                          }
                        })
                      } else {
                        wx.showToast({
                          title: '登录失败',
                          icon: 'error',
                          success: () => {
                            this.setData({
                              isPaySubmit: false
                            })
                            wx.switchTab({
                              url: '/pages/index/index',
                            })
                          }
                        })
                      }
                    },
                  })
                }
              } else {
                this.cancelPopup();
                this.getEntrustData();
              }

            } else {
              wx.showModal({
                title: '提示信息',
                content: res.msg,
                showCancel: false
              })
            }
          })
        }
      }
    })
  },

  /**
   * 发送短信
   * @param {*} worksInfo 
   * @param {*} adminInfo 
   * contents [委托人，艺术品名称，交易号]
   */
  sendNotifySms(worksInfo, adminInfo) {
    const bodyParams = {
      toPhone: adminInfo.standbyColeTwo,
      contents: [
        worksInfo.client,
        `摄影艺术品${worksInfo.worksName}`,
        `SY${worksInfo.id}`
      ],
      smsType: '8',
      templateId: 'adsf'
    }
    wxapi.sendNotifySms(bodyParams);
  },

  /**
   * 支付
   */
  payEntrust(params, bodyParams) {
    wxapi.entrustXcxPay(params, bodyParams).then(res => {
      wx.hideLoading();
      if (res.status === 200) {
        wx.requestPayment({
          nonceStr: res.data.nonceStr,
          package: res.data.packageValue,
          paySign: res.data.paySign,
          signType: res.data.signType,
          timeStamp: res.data.timeStamp,
          success: (res) => {
            this.data.isHandle = false;
            this.setData({
              showEntrust: false
            })
            wx.showToast({
              title: '购买成功',
              success: () => {
                this.getEntrustData();
              }
            })
          },
          fail: (res) => {
            this.data.isHandle = false;
            this.setData({
              showEntrust: false
            })
            if (res.errMsg.indexOf('fail cancel') !== -1) {
              wx.showToast({
                title: '交易取消',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '订单数据异常',
                icon: 'error'
              })
            }
          }
        })
      }
    })
  },

  /**
   * 取消弹窗
   */
  cancelPopup() {
    this.setData({
      showEntrust: false,
      showPhonecode: false,
      showLogistics: false,
      showOrder: false,
      entrustInfo: null,
      logisticsInfo: null,
      orderInfo: null,
      yesOrNo: null,
      isHandle: false,
      isTriggered: false
    })
  },

  /**
   * 撤销委托
   * @param {*} e 
   */
  retreatEntrust(e) {
    wx.showModal({
      title: '提示信息',
      content: '您确定要撤销该委托吗？',
      complete: (res) => {
        if (res.confirm) {
          const entrustMsg = e.currentTarget.dataset.entrustInfo;
          const headers = {
            Authorization: app.globalData.token
          }
          wxapi.entrustRetreat({ entrustId: entrustMsg.id }, headers).then(res => {
            if (res.status === 200) {
              wx.showToast({
                title: '撤销成功',
                success: () => {
                  this.getEntrustData();
                }
              })
            } else {
              wx.showModal({
                title: '提示信息',
                content: res.msg || res.message,
                showCancel: false
              })
            }
          })
        }
      }
    })
  },

  /**
   * 同意/不同意委托  1-同意 0-不同意
   * @param {*} e 
   */
  yesOrNoEntrust(e) {
    const entrustInfo = e.currentTarget.dataset.entrustInfo;
    const yesOrNo = e.currentTarget.dataset.entrustType;
    const yesOrNoText = yesOrNo == 1 ? '同意' : '不同意';
    wx.showModal({
      title: '提示信息',
      content: `您确定${yesOrNoText}该委托？`,
      complete: (res) => {
        if (res.confirm) {
          this.setData({
            entrustInfo,
            yesOrNo,
            showPhonecode: true
          })
        }
      }
    })
  },

  /**
   * 验证手机号
   * @param {*} e 
   */
  checkPhoneCode(e) {
    const value = e.detail;
    if (!value.smsCode) {
      wx.showToast({
        title: '填写验证码',
        icon: 'error'
      })
      return;
    }
    const bodyParams = {
      toPhone: value.entrustInfo.phoneNum,
      smsType: '7',
      code: value.smsCode,
      stk: value.entrustInfo.stk,
    };
    wxapi.verifySmsCode(bodyParams).then(res => {
      if (res.code === 20000) {
        if (value.entrustInfo.item === 1) {
          if (value.yesOrNo == 1) {
            const openId = wx.getStorageSync('openId');
            if (openId) {
              // 委托购买
              // const entrustParams = Object.assign({ stk: app.globalData.userInfo.cardNo, entrustType: 1 }, value.entrustInfo)
              this.payEntrust({ openId }, value.entrustInfo);
            } else {
              wx.login({
                success: (res) => {
                  if (res.code) {
                    const jsCode = res.code;
                    const headers = {
                      'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
                    }
                    wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
                      if (res.code === 20000) {
                        if (res.data) {
                          wx.setStorageSync('openId', res.data);
                          // 委托购买
                          // const entrustParams = Object.assign({ stk: app.globalData.userInfo.cardNo, entrustType: 1 }, value.entrustInfo)
                          this.payEntrust({ openId: res.data }, value.entrustInfo);
                        } else {
                          wx.hideLoading()
                          this.setData({
                            isPaySubmit: false
                          })
                          wx.showToast({
                            title: '获取openId失败',
                            icon: 'error'
                          })
                        }
                      } else {
                        wx.hideLoading();
                        wx.showModal({
                          title: '提示信息',
                          content: res.message,
                          showCancel: false
                        })
                      }
                    })
                  } else {
                    wx.showToast({
                      title: '登录失败',
                      icon: 'error',
                      success: () => {
                        this.setData({
                          isPaySubmit: false
                        })
                        wx.switchTab({
                          url: '/pages/index/index',
                        })
                      }
                    })
                  }
                },
              })
            }
          } else if (value.yesOrNo == 0) {
            this.yesOrNoEntrustBuy(value.entrustInfo, value.yesOrNo);
          }
        } else if (value.entrustInfo.item === 2) {
          this.yesOrNoEntrustSell(value.entrustInfo, value.yesOrNo)
        }
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 同意/不同意 委托出售
   * @param {*} entrustInfo 
   * @param {*} yesOrNo 
   */
  yesOrNoEntrustSell(entrustInfo, yesOrNo) {
    const params = {
      passiveEntrustId: entrustInfo.id,
      yesOrNo,
    }
    wxapi.yesOrNoSellPassiveEntrust(params).then(res => {
      if (res.status === 200) {
        wx.showToast({
          title: res.msg,
          success: () => {
            this.getEntrustData();
          }
        })
        this.cancelPopup();
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 同意/不同意 委托购买
   * @param {*} entrustInfo 
   * @param {*} yesOrNo 
   */
  yesOrNoEntrustBuy(entrustInfo, yesOrNo) {
    const params = {
      passiveEntrustId: entrustInfo.id,
      yesOrNo
    };
    wxapi.yesOrNoBuyPassiveEntrust(params).then(res => {
      if (res.status === 200) {
        wx.showToast({
          title: res.msg,
          success: () => {
            this.getEntrustData();
            this.cancelPopup();
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 支付
   */
  payEntrust(params, bodyParams) {
    wxapi.entrustXcxPay(params, bodyParams).then(res => {
      this.cancelPopup();
      if (res.status === 200) {
        wx.hideLoading();
        wx.requestPayment({
          nonceStr: res.data.nonceStr,
          package: res.data.packageValue,
          paySign: res.data.paySign,
          signType: res.data.signType,
          timeStamp: res.data.timeStamp,
          success: (res) => {
            this.cancelPopup();
            wx.showToast({
              title: '购买成功',
              success: () => {
                this.getEntrustData();
              }
            })
          },
          fail: (res) => {
            this.cancelPopup();
            if (res.errMsg.indexOf('fail cancel') !== -1) {
              wx.showToast({
                title: '交易取消',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '订单数据异常',
                icon: 'error'
              })
            }
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getEntrustData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})